<?php
namespace App\Backend\Controllers;

use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;
use App\Backend\Service\FileUploadService;
use  App\Libs\QiniuLibrary;
use Illuminate\Support\Facades\Storage;


class FileUploadController extends BaseController
{
    
    private $repository;
    public function __construct(FileUploadService $centerService)
    {
        $this->repository = $centerService;
    }
    public function upload(Request $request){
        header('Content-Type:text/html;charset=utf-8');
        header('Content-Type: application/json');
        if (!isset($_FILES['file'])) {
            $this->error('没有接收到文件');
        }
        if ($_FILES["file"]["error"] > 0){
            $msg="Error: " . $_FILES["file"]["error"] . "<br />";
            $this->error($msg);
        }else{
            $file = $_FILES['file'];
            $allow_type=['jpg', 'jpeg', 'png','apk'];
            $date = date('Ymd');
            $path='/file/'.$date.'/';
            $upload = new FileUploadService(true,$path,$allow_type);
            $res=$upload->upload_file($file);
            $result=[];
            if($res){
                $data=[
                    'path'=>$upload->get_imgurl(),
                    'path2'=>$upload->get_imgurl2(),
                    'type'=>$upload->get_type(),
                ];
                $this->success($data);
            }else{
                $this->error($upload->get_msg());
            }
        }

    }

    /**
     * 获取七牛云token
     */
    public function getQiniuToken()
    {
        $token = QiniuLibrary::Token('sls-assets');
        return $this->success(['token'=> $token]);
    }
    //上传图片-本地
    public function upload_image(Request $request)
    {
        $data=[
            'savename'=>$request->json("savename"),
        ];
        //file_put_contents('jjj.txt',json_encode($_REQUEST));
        if(empty($data['savename'])){
            $this->error("参数错误");

        }
        $this->repository->upload_image($request,$data);
    }
    //分片上传
    public function chuckimage(Request $request)
    {
        // 验证请求
        $request->validate([
            'c' => 'required|integer', // chunk
            't' => 'required|integer', // total chunks
            'n' => 'required|string',  // file name
            'u' => 'required|string',  // upload ID
            's' => 'required|integer', // file size
        ]);

        $chunk = $request->input('c');
        $chunks = $request->input('t');
        $fileName = $request->input('n');
        $uploadId = $request->input('u');
        $fileSize = $request->input('s');

        // 安全过滤文件名
        $fileName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $fileName);
        
        // 处理文件上传
        if ($request->hasFile('f')) {
            $file = $request->file('f');
            
            // 存储分片文件
            $chunkPath = "chunks/{$uploadId}";
            $chunkFile = "{$chunkPath}/{$fileName}.part{$chunk}";
            
            // 确保目录存在
            if (!Storage::exists($chunkPath)) {
                Storage::makeDirectory($chunkPath);
            }
            
            // 存储分片
            Storage::put($chunkFile, file_get_contents($file->getRealPath()));
            
            // 如果是最后一个分片，合并文件
            if ($chunk == $chunks - 1) {
                $finalPath = "uploads/{$uploadId}";
                $finalFile = "{$finalPath}/{$fileName}";
                
                // 确保目录存在
                if (!Storage::exists($finalPath)) {
                    Storage::makeDirectory($finalPath);
                }
                
                // 创建最终文件
                $finalStream = fopen(storage_path("app/{$finalFile}"), 'wb');
                
                // 合并所有分片
                for ($i = 0; $i < $chunks; $i++) {
                    $chunkFile = "chunks/{$uploadId}/{$fileName}.part{$i}";
                    $chunkStream = fopen(storage_path("app/{$chunkFile}"), 'rb');
                    stream_copy_to_stream($chunkStream, $finalStream);
                    fclose($chunkStream);
                    
                    // 删除分片文件
                    Storage::delete($chunkFile);
                }
                
                fclose($finalStream);
                
                // 删除分片目录
                Storage::deleteDirectory("chunks/{$uploadId}");
                
                // 生成完整的图片URL
                $imageUrl = Storage::url("app/{$finalFile}");

                $data=[
                        'savename'=>"/var/www/xf-162.lottefuture.com{$imageUrl}",
                    ];
                $imageUrl=$this->repository->return_upload_image($request,$data);
                return response()->json([
                    'success' => true,
                    'message' => '文件上传成功',
                    'path' => $finalFile,
                    'url' => $imageUrl,
                    'upload_id' => $uploadId
                ]);
            }
            
            return response()->json([
                'success' => true,
                'message' => '分片上传成功',
                'chunk' => $chunk,
                'upload_id' => $uploadId
            ]);
        }
        
        return response()->json(['error' => '没有接收到文件数据'], 400);
    }


    // 自定义函数检查上传限制
    public function check_upload_limits() {
        $max_upload = ini_get('upload_max_filesize');
        $max_post = ini_get('post_max_size');
        $memory_limit = ini_get('memory_limit');
        
        return [
            'upload_max_filesize' => $max_upload,
            'post_max_size' => $max_post,
            'memory_limit' => $memory_limit
        ];
    }




}
